<template>
    <div>
        <div>
            <p>
            <textarea v-model="state.commentText"></textarea>
            </p>
            <p>
            <button @click="addComment">提交评论</button>
            </p>
        </div>
        <!-- 回复评论 -->
        <div>
            <ul>
            <comment-comp :data="state.commentTree" @add-reply="addReply"></comment-comp>
            </ul>
        </div>
</div>
</template>
<script setup>
import { reactive } from "vue";
import useUserInfo from "../../store/user.js";
import CommentComp from './CommentComp.vue';

const userInfoStore = useUserInfo();

const state = reactive({
  commentText: "",
  commentTree: formatTree(getComment("one")),
});

const addComment = () => {
  const { id, username } = userInfoStore.userInfo;
  const commentInfo = {
    id: new Date().getTime(),
    pid: 0,
    uid: id,
    username,
    comment: state.commentText,
    createdAt: new Date().toISOString(),
  };
  setComment("one", commentInfo);
  state.commentTree.unshift(commentInfo);
  state.commentText = "";

};
const addReply = (item,replyText) => {

    const {id, username} = userInfoStore.userInfo;
    const replyInfo = {
        id: new Date().getTime(),
        pid: item.id,
        uid: id,
        username,
        comment: replyText,
        createdAt: new Date().toISOString(),
    }
    ;(item.children || (item.children = [])).unshift(replyInfo);
    setComment("one", replyInfo);
}

function getComment(field) {
  return JSON.parse(localStorage.getItem(field) || "[]");
};
function setComment (field, comment) {
  const commentList = JSON.parse(localStorage.getItem(field) || "[]");
  commentList.unshift(comment);
  localStorage.setItem(field, JSON.stringify(commentList));
};

function formatTree(data){
    const result = [];
    const map={
        /**
         * 1:item,
         * 2:item
         */
    }
    data.forEach(item=>{
        map[item.id] = item;
    })
    data.forEach(item=>{
        const parent =map[item.pid];
        if(parent){
            ;(parent.children || (parent.children = [])).unshift(item);
        }else {
            result.unshift(item);
        }
    })
    return result;
}
</script>
<style lang="scss" scoped></style>
